from django.utils import timezone
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from users.models import User

from goods.models import GoodsVisitCount
from meiduo_admin.serializer.statistical import GoodsDayViewSerializer


class UserTotalCountView(APIView):
    permission_classes = [IsAdminUser]
    def get(self, request):
        now_date = timezone.now()
        count = User.objects.count()

        response_date = {
            'date': now_date.date(),
            'count': count
        }
        return Response(response_date)


class UserDayIncrementView(APIView):
    permission_classes = [IsAdminUser]
    def get(self, request):
        now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        count = User.objects.filter(date_joined__gte=now_date).count()

        response_date = {
            'date': now_date.date(),
            'count': count
        }

        return Response(response_date)

class UserDayActiveView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        count = User.objects.filter(last_login__gte=now_date).count()

        response_date = {
            'date': now_date.date(),
            'count': count
        }

        return Response(response_date)

class UserDayOrdersView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        count = User.objects.filter(orders__create_time__gte=now_date).distinct().count()

        response_date = {
            'date': now_date.date(),
            'count': count
        }

        return Response(response_date)
class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        begin_date=now_date-timezone.timedelta(days=29)

        currunt_date=begin_date

        month_li=[]
        while currunt_date <= now_date:
            next_date=currunt_date+timezone.timedelta(days=1)
            count=User.objects.filter(date_joined__gte=currunt_date,
                                      date_joined__lt=next_date).count()
            month_li.append({
                'count':count,
                'date':currunt_date.date()
            })
            currunt_date+=timezone.timedelta(days=1)
        return Response(month_li)

class GoodsDayView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        now_date=timezone.now().date()
        goods_visit=GoodsVisitCount.objects.filter(date=now_date)

        serializer=GoodsDayViewSerializer(goods_visit)

        return Response(serializer.data)

